package org.example.erat.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 报告数据加载器
 * 用于在应用启动时加载示例报告数据
 */
@Component
@RequiredArgsConstructor
@Order(3) // 在其他数据初始化之后执行
@Slf4j
public class ReportDataLoader implements CommandLineRunner {

    private final DataSource dataSource;

    @Override
    public void run(String... args) {
        log.info("开始加载报告数据...");
        
        try {
            // 创建资源数据库填充器
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.addScript(new ClassPathResource("report-data.sql"));
            populator.setContinueOnError(true); // 如果出错继续执行
            
            // 执行 SQL 脚本
            populator.execute(dataSource);
            
            log.info("报告数据加载完成");
        } catch (Exception e) {
            log.error("加载报告数据失败", e);
        }
    }
}
